import React, { useEffect,useState } from 'react'
import { useNavigate} from 'react-router-dom';
import { Layout, Menu } from 'antd';
import './index.css'
import axios from 'axios'
import {connect} from 'react-redux' 
const { Sider } = Layout;


const rootSubmenuKeys = ['sub1', 'sub2', 'sub4'];
function SideMenu(props) {

  const [menu,setMenu]=useState([])
  const [openKeys, setOpenKeys] = useState(['sub1']);
  const navigate = useNavigate();
  useEffect(()=>{
    axios.get("http://localhost:8000/rights?_embed=children").then(res=>{
      console.log('data',res.data);
      const {data}=res
          // console.log(data);
          setMenu(data)
          // })   
          })       
  },[])
  const obj = (key, label, children) => {
    return {
      key,
      label,
      children,
    }
  }
  const {role:{rights},username}=JSON.parse(localStorage.getItem('token'))
  // console.log(username);
  // console.log(rights);
  const checkPagePermission = (item)=>{
    return item.pagepermisson&&rights.includes(item.key)
  }
  const dfs1 = (data) => {
    const arr =[]
    data.map((item) => {
      if (item.children && item.children.length !== 0) {
        return checkPagePermission(item) && arr.push(
          obj(item.key,  item.title, dfs1(item.children))
        )
      } else {
        return (
          checkPagePermission(item)
           &&
          arr.push(obj(item.key,  item.title))
        )
      }
    })
    return arr
  }

  const onOpenChange = (keys) => {
    const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1);
    if (rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      setOpenKeys(keys);
    } else {
      setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
    }
  };
  const openSelect=["/"+window.location.pathname.split("/")[1]]
  return (
    <Sider trigger={null} collapsible collapsed={props.isCollapsed} style={{height:'120%'}}>
      <div style={{display:'flex',height:"100%","flexDirection":"column"}}>
        <div className="logo" >全球新闻发布管理系统</div>
       
       <div style={{flex:1,"overflow":"auto"}}>
   <Menu
      mode="inline"
      theme="dark"
      selectedKeys={window.location.pathname}
      defaultOpenKeys={openSelect}
      // openKeys={openKeys}
      onOpenChange={onOpenChange}
      items= {dfs1(menu)}
      onClick={(e)=>navigate(e.key)}
      >
    </Menu>
    </div>
    </div>
 </Sider>
  )
}
const mapStateToProps=({CollApsedReducer:{isCollapsed}})=>(
  {
    isCollapsed
    }
)
export default  connect(mapStateToProps)(SideMenu)